import os
import argparse

print('WARNING: this script change filenames')
def dir_path(string):
    if os.path.isdir(string):
        return string
    else:
        raise NotADirectoryError(string)

parser = argparse.ArgumentParser()
parser.add_argument('--dir', type=dir_path)
args = parser.parse_args()

if(not args.dir or len(args.dir) == 0):
	print('Mandatory --dir parameter')

else:
	dir = args.dir
	tedi_files = list()
	list_dir = os.listdir(dir)
	
	
	
	for file in list_dir:
		if file.endswith(".te"):
			tedi_files.append(os.path.join(dir, file))
		
	if(len(tedi_files) == 1):
		print('Found tedi file, using it as index.te')
		os.rename(tedi_files[0], dir + 'index.te')
		img_files = list()
		i = 0
		line = ''

		f = open(os.path.join(dir, "index.te"), "r")
		lines = f.read()
		for file in os.listdir(dir):
			if not file.endswith(".te"):
				if lines.find(file) != -1:
					print('Renaming ' + file + ' to nibis style')
					lines = lines.replace('] ' + file + ')', '] image' + str(i) + ')')
					os.rename(dir + file, dir + 'image' + str(i))
					i += 1
		f.close()

		f = open(os.path.join(dir, "index.te"), "w")

		f.write(lines)
		f.close()
	else:
		if(dir + 'index.te' in tedi_files):
			print('Found multiple tedi files with a index.te file')
			f = open(os.path.join(dir, "index.te"), "r")
			lines = f.readlines()
			complete_text = ""
			for line in lines:
				if(len(line) > 0 and line[0] == '+'):
					try:
						print('Found inserted file: ' + line[1:-1])
						include = open(os.path.join(dir, line[1:-1]), "r")
						include_text = include.readlines()
						for new_line in include_text:
							complete_text += new_line

						include.close()
						print('Inserted file added to index.te')
					except:
						complete_text += line
						print('Failed inserted file')
					
				else:
					complete_text += line
			f.close()
			i = 0
			for file in os.listdir(dir):
				if not file.endswith(".te"):
					if file in complete_text:
						print('Renaming ' + file + ' to nibis style')
						complete_text = complete_text.replace('] ' + file + ')', '] image' + str(i) + ')')
						os.rename(dir + file, dir + 'image' + str(i))
						i += 1
				elif file not in "index.te":
					os.remove(os.path.join(dir, file))
					
			f = open(os.path.join(dir, "index.te"), "w")
			f.write(complete_text)
			f.close()
		else:
			print('If there are multiples tedi files, this script needs one named index.te to be the main one')
	
